import React, { useEffect, useState } from 'react'
import { fetchWeatherApi } from 'openmeteo'

interface WeatherData {
    temperature: number
    weathercode: number
}

const weatherIcons: Record<number, string> = {
    0: '☀️',
    1: '🌤',
    2: '⛅️',
    3: '☁️',
    45: '🌫',
    48: '🌫',
    51: '🌦',
    61: '🌧',
    71: '❄️',
    95: '⛈',
}

const Weather: React.FC = () => {
    const [weather, setWeather] = useState<WeatherData | null>(null)
    const [location, setLocation] = useState<string>('')

    const url = 'https://api.open-meteo.com/v1/forecast'

    useEffect(() => {
        navigator.geolocation.getCurrentPosition(async (pos) => {
            const { latitude, longitude } = pos.coords
            const params = {
                latitude: latitude,
                longitude: longitude,
                current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m',
                hourly: 'temperature_2m,precipitation',
                daily: 'weather_code,temperature_2m_max,temperature_2m_min'
            };
            const res = await fetchWeatherApi(
                url, params
            )
            console.log(res[0]);
            const temperature = res[0].current()!.variables(0)!.value()
            const weatherCode = res[0].current()!.variables(1)!.value()

            const data: WeatherData = {
                temperature: temperature,
                weathercode: weatherCode
            }
            console.log(data);

            setWeather(data)

            // 反查地名（可选）
            const locRes = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`, {
                headers: {
                    // 👇 这是关键！替换为你自己的应用名和联系方式
                    'User-Agent': 'MyWeatherApp/1.0 (313540137@qq.com)'
                    // 或者 'User-Agent': 'MyWeatherApp/1.0 (https://mywebsite.com/contact)'
                }
            })//测试环境由于跨域会失败
            const locData = await locRes.json()
            setLocation(locData.address.city || locData.address.state || '')
        })
    }, [])

    if (!weather) return <div className="text-white">Loading weather...</div>

    const weatherUrl = `https://www.msn.com/zh-cn/weather/search?q=${encodeURIComponent(location)}`

    return (
        <a href={weatherUrl} target="_blank" rel="noopener noreferrer">
            <div className="text-white text-sm mt-4 text-center">
                <div>{location || '📍'}</div>
                <div>{weatherIcons[weather.weathercode] || '🌈'} {weather.temperature.toFixed(2)}°C</div>
            </div>
        </a>

    )
}

export default Weather
